package mysql

import (
	"bluebell-backend/common"
	"bluebell-backend/model/po"
	"fmt"
	"strconv"
	"sync"
)

var postDao *PostDao
var postOnce sync.Once

type PostDao struct {
}

func NewPostDaoInstance() *PostDao {
	postOnce.Do(
		func() {
			postDao = &PostDao{}
		})
	return postDao
}

func (*PostDao) InsertPost(post *po.Post) (int, error) {
	if err := db.Create(post).Error; err != nil {
		return common.ERROR, err
	}
	return common.SUCCESS, err
}

func (*PostDao) UpdatePost(post *po.Post) (int, error) {
	err := db.Save(post).Error
	if err != nil {
		return common.ERROR, err
	}
	return common.SUCCESS, nil
}

func (*PostDao) GetOnePostById(id int64) (*po.Post, error) {

	var post po.Post
	if err := db.Where("id = ?", id).First(&post).Error; err != nil {
		return nil, err
	}
	return &post, nil
}

func (*PostDao) GetPostListByCategoryId(cId int64) ([]*po.Post, error) {
	var postList []*po.Post
	if err := db.Where("cid = ?", cId).Find(&postList).Error; err != nil {
		return nil, err
	}
	return postList, nil
}

// 批量查询，这里注意的是，ids传过来的就是已经排好序的了，这里要根据ids的顺序进行查询
func (*PostDao) GetPostListByIds(ids []string) ([]*po.Post, error) {
	var postList []*po.Post
	err := db.Where("p_id in (?)", ids).Find(&postList).Error
	if err != nil {
		fmt.Println("查询失败")
		return nil, err
	}

	// 根据ids的顺序排序 ！！！
	posts := make([]*po.Post, len(postList))
	//for index, id := range ids {
	//	for _, post := range postList {
	//		parseInt, _ := strconv.ParseInt(id, 10, 64)
	//		if post.PId == parseInt {
	//			posts[index] = post
	//		} else {
	//			continue
	//		}
	//	}
	//}

	// go中没有判断切片中是否存在某个元素的方法，需要转为map
	m := make(map[int64]interface{}, len(postList))
	for _, post := range postList {
		m[post.PId] = post
	}

	for index, id := range ids {
		pid, _ := strconv.ParseInt(id, 10, 64)
		post, ok := m[pid]
		if ok {
			posts[index] = post.(*po.Post)
		}
	}

	return posts, nil
}
